package com.alibaba.algo.core.exception.handle;

import com.alibaba.algo.core.contant.SysConstant;
import com.alibaba.algo.core.exception.BaseException;
import com.alibaba.algo.core.exception.IllegalInputArgumentException;
import com.alibaba.algo.core.resp.BaseResult;
import com.fasterxml.jackson.databind.JsonMappingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 全局业务异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public BaseResult exceptionHandler(BaseException ex) {
        Integer errorCode = ex.getErrorCode();
        String message = ex.getErrorMsg();
        log.error("BaseException--->{}", ExceptionUtils.getStackTrace(ex));
        return BaseResult.buildError(errorCode, message);
    }

    /**
     * 接口参数校验
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(IllegalInputArgumentException.class)
    public Object exceptionHandler(IllegalInputArgumentException ex) {
        log.error("IllegalInputArgumentException--->{}", ExceptionUtils.getStackTrace(ex));
        return BaseResult.buildError(ex.getErrorCode(), ex.getMessage());
    }

    /**
     * 接口参数校验
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Object handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        log.error("HttpMessageNotReadableException--->{}", ExceptionUtils.getStackTrace(ex));
        return BaseResult.buildError(SysConstant.SYS_ERROR, "参数不合法!", ex.getMessage());
    }


    /**
     * 全局未知异常
     *
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public BaseResult exceptionHandler(HttpServletRequest request, Exception ex) {
        log.error("Exception--->{}", ExceptionUtils.getStackTrace(ex));
        log.error("Exception message--->{}", ex.getMessage());
        String message = StringUtils.hasLength(ex.getMessage()) ? ex.getMessage() : request.getRequestURI();
        return BaseResult.buildError(SysConstant.SYS_ERROR, message);
    }


}
